package com.atguigu.test1;

import java.security.cert.CertPathChecker;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadMes {
    public static void main(String[] args) {
        Source source = new Source();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
//                    Thread.sleep(100);
                    source.increment();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
//                    Thread.sleep(200);
                    source.decrement();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
//                    Thread.sleep(300);
                    source.increment();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) {
//                    Thread.sleep(400);
                    source.decrement();
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();

    }
}


// V1 synchronized + wait + notifyAll 传统老版本
class Source{
    private int number = 0;
/*
    public synchronized void increment() throws InterruptedException {
        while (number != 0) wait();
        System.out.print(Thread.currentThread().getName());
        System.out.println(" 添加之后的值为: " + (++number));
        notifyAll();
    }
    public synchronized void decrement() throws InterruptedException {
        while (number != 1) wait();
        System.out.print(Thread.currentThread().getName());
        System.out.println(" 减少之后的值为: " + (--number));
        notifyAll();
    }
    */
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
public void increment() throws InterruptedException {
    lock.lock();
    try {
        while (number != 1) { condition.await(); }
        System.out.print(Thread.currentThread().getName());
        System.out.println(" 减少之后的值为: " + (--number));
        condition.signalAll();
    }finally {
        lock.unlock();
    }
}
    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            while (number != 0) { condition.await(); }
            System.out.print(Thread.currentThread().getName());
            System.out.println(" 增加之后的值为: " + (++number));
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }
}
